<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="设备ID" prop="deviceId">
              <el-input v-model="queryParams.deviceId" placeholder="请输入设备ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="queryParams.latitude" placeholder="请输入纬度" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="queryParams.longitude" placeholder="请输入经度" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="记录时间" prop="recordTime">
              <el-date-picker clearable v-model="queryParams.recordTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择记录时间" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['authcode:deviceLocation:add']"> 新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['authcode:deviceLocation:edit']"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['authcode:deviceLocation:remove']"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['authcode:deviceLocation:export']">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="deviceLocationList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column label="设备ID" align="center" prop="deviceId" width="180" />
        <el-table-column label="纬度" align="center" prop="latitude" />
        <el-table-column label="经度" align="center" prop="longitude" />
        <el-table-column label="定位精度(米)" align="center" prop="accuracy" />
        <el-table-column label="海拔" align="center" prop="altitude" />
        <el-table-column label="速度(m/s)" align="center" prop="speed" />
        <el-table-column label="方向角" align="center" prop="bearing" />
        <el-table-column label="定位时间" align="center" prop="locationTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.locationTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="记录时间" align="center" prop="recordTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.recordTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="地理位置描述" align="center" prop="address" width="180" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['authcode:deviceLocation:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['authcode:deviceLocation:remove']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="地图" placement="top">
              <el-button
                link
                type="primary"
                icon="Search"
                @click="handleUpdate_map(scope.row)"
                v-hasPermi="['authcode:deviceLocation:edit']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改设备位置记录对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="deviceLocationFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备ID" prop="deviceId">
          <el-input v-model="form.deviceId" placeholder="请输入设备ID" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入纬度" />
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="定位精度" prop="accuracy">
          <el-input v-model="form.accuracy" placeholder="请输入定位精度(米)" />
        </el-form-item>
        <el-form-item label="海拔" prop="altitude">
          <el-input v-model="form.altitude" placeholder="请输入海拔" />
        </el-form-item>
        <el-form-item label="速度(m/s)" prop="speed">
          <el-input v-model="form.speed" placeholder="请输入速度(m/s)" />
        </el-form-item>
        <el-form-item label="方向角" prop="bearing">
          <el-input v-model="form.bearing" placeholder="请输入方向角" />
        </el-form-item>
        <el-form-item label="定位时间" prop="locationTime">
          <el-date-picker clearable v-model="form.locationTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择定位时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="记录时间" prop="recordTime">
          <el-date-picker clearable v-model="form.recordTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择记录时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="地理位置" prop="address">
          <el-input v-model="form.address" placeholder="请输入地理位置描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 地图显示对话框 -->
    <el-dialog :title="dialog_map.title" v-model="dialog_map.visible" width="500px" append-to-body>
      <div class="map-container">
        <div id="container" style="width: 100%; height: 600px"></div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel_map">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DeviceLocation" lang="ts">
import { listDeviceLocation, getDeviceLocation, delDeviceLocation, addDeviceLocation, updateDeviceLocation } from '@/api/authcode/deviceLocation';
import { DeviceLocationVO, DeviceLocationQuery, DeviceLocationForm } from '@/api/authcode/deviceLocation/types';
import AMapLoader from '@amap/amap-jsapi-loader';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const deviceLocationList = ref<DeviceLocationVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const deviceLocationFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

let map = null;
let marker = null;

const initMap = () => {
  // 这里使用高德地图API示例
  AMapLoader.load({
    key: '710e16103b8cd8577c4dee53e7886aef', // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  })
    .then((AMap) => {
      map = new AMap.Map('container', {
        // 设置地图容器id
        viewMode: '3D', // 是否为3D地图模式
        zoom: 14, // 初始化地图级别
        // center: [114.05454, 22.52291] // 初始化地图中心点位置
        center: [116.397428, 39.90923] // 初始化地图中心点位置
        // center: [form.value.longitude, form.value.latitude] // 初始化地图中心点位置
      });
    })
    .catch((e) => {
      console.log(e);
    });
};

// 初始化地图
const mapView = () => {
  AMapLoader.load({
    //可多次调用load
    key: '710e16103b8cd8577c4dee53e7886aef', // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  })
    .then((AMap) => {
      if (map == null) {
        map = new AMap.Map('container', {
          // 设置地图容器id
          viewMode: '3D', // 是否为3D地图模式
          zoom: 14, // 初始化地图级别
          // center: [114.05454, 22.52291] // 初始化地图中心点位置
          center: [116.397428, 39.90923] // 初始化地图中心点位置
          // center: [form.value.longitude, form.value.latitude] // 初始化地图中心点位置
        });
      }
      // 清除旧标记
      if (marker != null) {
        map.remove(marker);
        marker = null;
      }
      const position = new AMap.LngLat(form.value.longitude, form.value.latitude); //Marker 经纬度
      //点标记显示内容
      const markerContent = `<div class="custom-content-marker">
      <img src="//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png">
      </div>`;
      marker = new AMap.Marker({
        position: position,
        content: markerContent, //将 html 传给 content form.value.address
        offset: new AMap.Pixel(-13, -30) //以 icon 的 [center bottom] 为原点
      });
      // marker.setMap(map);
      map.add(marker);
      map.setCenter([form.value.longitude, form.value.latitude]);
      // 添加信息窗口
      const infoWindow = new AMap.InfoWindow({
        content: `
              <div>
                <h4>设备ID：${form.value.deviceId}</h4>
                <p>位置: ${form.value.address}</p>
                <p>时间: ${new Date(form.value.locationTime).toLocaleString()}</p>
              </div>
            `
      });
      //打开信息窗体
      infoWindow.open(map, [form.value.longitude, form.value.latitude]);
    })
    .catch((e) => {
      console.error(e);
    });
};

const dialog_map = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: DeviceLocationForm = {
  id: undefined,
  deviceId: undefined,
  latitude: undefined,
  longitude: undefined,
  accuracy: undefined,
  altitude: undefined,
  speed: undefined,
  bearing: undefined,
  locationTime: undefined,
  recordTime: undefined,
  address: undefined
};
const data = reactive<PageData<DeviceLocationForm, DeviceLocationQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceId: undefined,
    latitude: undefined,
    longitude: undefined,
    accuracy: undefined,
    altitude: undefined,
    speed: undefined,
    bearing: undefined,
    locationTime: undefined,
    recordTime: undefined,
    address: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键不能为空', trigger: 'blur' }],
    deviceId: [{ required: true, message: '设备ID不能为空', trigger: 'blur' }],
    latitude: [{ required: true, message: '纬度不能为空', trigger: 'blur' }],
    longitude: [{ required: true, message: '经度不能为空', trigger: 'blur' }],
    locationTime: [{ required: true, message: '定位时间不能为空', trigger: 'blur' }],
    recordTime: [{ required: true, message: '记录时间不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询设备位置记录列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDeviceLocation(queryParams.value);
  deviceLocationList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** map取消按钮 */
const cancel_map = () => {
  reset();
  dialog_map.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  deviceLocationFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: DeviceLocationVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加设备位置记录';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: DeviceLocationVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getDeviceLocation(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改设备位置记录';
};

/** 修改按钮操作 */
const handleUpdate_map = async (row?: DeviceLocationVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getDeviceLocation(_id);
  Object.assign(form.value, res.data);
  mapView(); //初始化地图
  dialog_map.visible = true;
  dialog_map.title = '地图';
};

/** 提交按钮 */
const submitForm = () => {
  deviceLocationFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateDeviceLocation(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addDeviceLocation(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: DeviceLocationVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除设备位置记录编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delDeviceLocation(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'authcode/deviceLocation/export',
    {
      ...queryParams.value
    },
    `deviceLocation_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
  initMap();
});

onUnmounted(() => {
  map = null;
});
</script>
